//
//  AppDelegate.m
//  liangyi
//
//  Created by 张水 on 16/12/12.
//  Copyright © 2016年 yswh. All rights reserved.
//

#import "AppDelegate.h"
#import "AppHeader.h"
#import "AFNetworking.h"
#import "LaunchViewController.h"
#import "MainViewController.h"
#import "MineViewController.h"
#import "LoginViewController.h"
#import "MyschemeViewController.h"
#import <MediaPlayer/MediaPlayer.h>
//#import "YSWhNavigationController.h"
#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#import <UserNotifications/UserNotifications.h>
#endif


@interface AppDelegate ()<JPUSHRegisterDelegate>

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    [self setupSDK];
    [self setupPush:launchOptions];
    [self SetupAppStyle];
    [self BuildPropertys];
    [self buildRootViewController];
    return YES;
}

#pragma mark - application cycle  Push Notification
- (void)setupPush:(NSDictionary *)launchOptions {
    
    //JPush
    [JPUSHService setupWithOption:launchOptions
                           appKey:@"71858db3b50cd5dedf17cb59"
                          channel:@"App Store"
                 apsForProduction:NO];
    [JPUSHService  setLogOFF];

    if ([[UIDevice currentDevice].systemVersion floatValue] >= 10.0) {
        //iOS10以上
        JPUSHRegisterEntity * entity = [[JPUSHRegisterEntity alloc] init];
         entity.types = JPAuthorizationOptionAlert|JPAuthorizationOptionBadge|JPAuthorizationOptionSound;
        [JPUSHService registerForRemoteNotificationConfig:entity delegate:self];
    }else{
        //iOS8以上可以添加自定义categories
        [JPUSHService registerForRemoteNotificationTypes:(UIUserNotificationTypeBadge |
                                                          UIUserNotificationTypeSound |
                                                          UIUserNotificationTypeAlert)
                                              categories:nil];
    }
    

    [JPUSHService registrationIDCompletionHandler:^(int resCode, NSString *registrationID) {
        if(resCode == 0){
            NSLog(@"registrationID获取成功：%@",registrationID);
            NSString *userLogin = [CommonMethod fuckNULL:[UserDefaultsUtlis getValueForKey:@"userid"]];
            
            __autoreleasing NSMutableSet *tags = [NSMutableSet set];
            __autoreleasing NSString *alias = [NSString stringWithFormat:@"doc%@",userLogin];
            [JPUSHService setTags:tags alias:alias fetchCompletionHandle:^(int iResCode, NSSet *iTags, NSString *iAlias) {
                NSLog(@"rescode: %d, \ntags: %@, \nalias: %@\n", iResCode, iTags, iAlias);
            }];
        }
        else{
            NSLog(@"registrationID获取失败，code：%d",resCode);
        }
    }];
}
- (void)applicationWillEnterForeground:(UIApplication *)application {
    [application setApplicationIconBadgeNumber:0];
    [application cancelAllLocalNotifications];
    
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
    [JPUSHService setBadge:0];
    
}

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    
    [JPUSHService registerDeviceToken:deviceToken];
    
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
    
    [JPUSHService handleRemoteNotification:userInfo];
    
    if (application.applicationState == UIApplicationStateActive) {
        //程序运行时收到通知，先弹出消息框
        [self getPushMessageAtStateActive:userInfo];
    }
    else{
        //程序已经关闭或者在后台运行
        [self pushToViewControllerWhenClickPushMessageWith:userInfo];
    }
    
    [application setApplicationIconBadgeNumber:0];
    [JPUSHService handleRemoteNotification:userInfo];
}
#ifdef NSFoundationVersionNumber_iOS_9_x_Max
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger))completionHandler {
    // Required
    NSDictionary * userInfo = notification.request.content.userInfo;
    if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
    }
    completionHandler(UNNotificationPresentationOptionAlert); // 需要执行这个方法，选择是否提醒用户，有Badge、Sound、Alert三种类型可以选择设置
}

- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler {
    // Required
    NSDictionary * userInfo = response.notification.request.content.userInfo;
    if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
    }
    completionHandler();  // 系统要求执行这个方法
}
#endif


#if __IPHONE_OS_VERSION_MAX_ALLOWED > 100000
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<UIApplicationOpenURLOptionsKey, id> *)options
{
    BOOL result = [UMSocialSnsService handleOpenURL:url];
    if (!result) {
        // 其他如支付等SDK的回调
    }
    return result;
}

#endif

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
    BOOL result = [UMSocialSnsService handleOpenURL:url];
    if (!result) {
        // 其他如支付等SDK的回调
    }
    return result;
}

- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
{
    BOOL result =  [UMSocialSnsService handleOpenURL:url];
    if (!result) {
        // 其他如支付等SDK的回调
    }
    return result;
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    
    [JPUSHService handleRemoteNotification:userInfo];
    
    completionHandler(UIBackgroundFetchResultNewData);
    
    if (application.applicationState == UIApplicationStateActive) {
        //程序运行时收到通知，先弹出消息框
        [self getPushMessageAtStateActive:userInfo];
    }
    else{
        //程序已经关闭或者在后台运行
        [self pushToViewControllerWhenClickPushMessageWith:userInfo];
    }
    
    [application setApplicationIconBadgeNumber:0];
    
    [JPUSHService handleRemoteNotification:userInfo];
    
    completionHandler(UIBackgroundFetchResultNewData);
    
    
}

- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    NSLog(@"did Fail To Register For Remote Notifications With Error: %@", error);
}

-(void)setupSDK{
    BuglyConfig *config = [[BuglyConfig alloc] init];
    config.unexpectedTerminatingDetectionEnable = YES;
    [Bugly startWithAppId:@"0c3f90e50a" config:config];
    [UMSocialData openLog:NO];
    
    [UMSocialData setAppKey:@"58aa453b6e27a4238d0008ae"];
    [UMSocialWechatHandler setWXAppId:@"wx17bf01741df47613" appSecret:@"" url:@"http://doctor.bjmvc.com/"];
    [UMSocialQQHandler setQQWithAppId:@"1105855652" appKey:@"JnipOR3Bmx8NUji5" url:@"http://doctor.bjmvc.com/"];
    [UMSocialQQHandler setSupportWebView:YES];
    
    [UMSocialSinaSSOHandler openNewSinaSSOWithAppKey:@"1672858578" secret:@"437d03aa28a85a38f1595be2660d2ae7" RedirectURL:@"http://doctor.bjmvc.com/"];
    [UMSocialSinaSSOHandler openNewSinaSSOWithRedirectURL:@"http://doctor.bjmvc.com/"];

    [UMSocialConfig hiddenNotInstallPlatforms:@[UMShareToWechatSession,UMShareToWechatTimeline,UMShareToSina,UMShareToQQ,UMShareToQzone]];
//    [[UMSocialManager defaultManager]openLog:YES];
//    [[UMSocialManager defaultManager]setUmSocialAppkey:@"58aa453b6e27a4238d0008ae"];
//    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_WechatSession appKey:@"wx17bf01741df47613" appSecret:@"3baf1193c85774b3fd9d18447d76cab0" redirectURL:nil];
//    [[UMSocialManager defaultManager] removePlatformProviderWithPlatformTypes:@[@(UMSocialPlatformType_WechatFavorite)]];
//    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_QQ appKey:@"1105855652"/*设置QQ平台的appID*/  appSecret:@"JnipOR3Bmx8NUji5" redirectURL:nil];
//    @"http://yswh.bjmvc.com/dyapp.html"
//   [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_Sina appKey:@"3921700954"  appSecret:@"04b48b094faeb16683c32669824ebdad" redirectURL:nil];
}
-(void)SetupAppStyle{
    [[UINavigationBar appearance]setTintColor:[UIColor whiteColor]];
    [[UINavigationBar appearance]setBarTintColor:[UIColor ColorWithHex:@"#5bc4d2"]];
    [[UINavigationBar appearance]setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor whiteColor],NSFontAttributeName:
                                                              [UIFont fontWithName:@"AmericanTypewriter-Bold" size:17]}];

}
-(void)BuildPropertys{
    
    [MagicalRecord setupCoreDataStack];
    
    self.deviceID = [CommonMethod fuckNULL:[UserDefaultsUtlis getValueForKey:@"deviceID"]];
    
    if ([self.deviceID isEqualToString:@""]){
        self.deviceID = [CommonMethod fuckNULL:[UIDevice currentDevice].identifierForVendor.UUIDString];
        if(self.deviceID.length == 0){
            NSString *str = [[NSString stringWithFormat:@"%@",[NSDate date]]md5Encrypt];
            if (str.length > 20){
                self.deviceID = [str substringToIndex:20];
            }else{
                self.deviceID = str;
            }
        }
        [UserDefaultsUtlis saveValue:self.deviceID forKey:@"deviceID"];
    }
}

- (void)buildNotification {
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(buildLoginViewController) name:KNotificationBuildLoginVC object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(buildMainViewController) name:KNotificationBuildMainVC object:nil];
}

-(void)buildRootViewController{
    
    _window = [[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
    _window.backgroundColor = [UIColor whiteColor];
    [_window makeKeyAndVisible];
    LaunchViewController *lanuch = [LaunchViewController new];
    _window.rootViewController = lanuch;
    
    //    if (userLogin.length > 0) {
    //
    //        [self checkUserLogin];
    //    }else{
    //        [self buildLoginViewController];
    //    }

    [self buildMainViewController];
    
}
-(void)buildLoginViewController{
    LoginViewController *loginVC  = [LoginViewController new];
    UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:loginVC];
    _window.rootViewController = nav;
    [_window makeKeyAndVisible];
}
-(void)buildMainViewController{
    MainViewController *mainVC = [[MainViewController alloc]init];
    MineViewController *mineVC = [[MineViewController alloc]init];
    _window.backgroundColor = [UIColor ColorWithHex:@"#333942"];
    
    self.mainNavigationController = [[UINavigationController alloc]initWithRootViewController:mainVC];
    self.LeftSlideVC = [[LeftSlideViewController alloc]initWithLeftView:mineVC andMainView:self.mainNavigationController];
    _window.rootViewController = self.LeftSlideVC;
    
    [_window makeKeyAndVisible];
    NSString *first = [CommonMethod fuckNULL:[UserDefaultsUtlis getValueForKey:@"first"]];
    if (first == nil) {
        [GuideViewController show];
    }
}

//-(void)checkUserLogin {
//    NSString *url = [BASEURL stringByAppendingString:@""];
//    NSDictionary *parameters = @{@"memberId":[UserDefaultsUtlis getValueForKey:@"userid"],
//                                 @"login":[NSString stringWithFormat:@"%@@@%@",[UserDefaultsUtlis getValueForKey:@"userid"],ApplicationDelegate.deviceID]};
//    [AppNetwork requestWithPath:url parameters:parameters success:^(id responseObject) {
//        NetworkModel *network = [NetworkModel mj_objectWithKeyValues:responseObject];
//        NSLog(@"%@",responseObject);
//        NSInteger code = network.code.integerValue;
//        if (code != 0 ){
//            [self buildMainViewController];
//        }else{
//            [self buildRootViewController];
//        }
//    } failure:^(id error) {
//        [self buildMainViewController];
//    }];
//}


-(void)getPushMessageAtStateActive:(NSDictionary *)pushMessageDic{
    
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@""  message:[[pushMessageDic objectForKey:@"aps"]objectForKey:@"alert"]   preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *confirmAction = [UIAlertAction actionWithTitle:@"查看"  style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                [self pushToViewControllerWhenClickPushMessageWith:pushMessageDic];
       }];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消"   style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {      }];
    [alertController addAction:confirmAction];
    [alertController addAction:cancelAction];
    [self.window.rootViewController presentViewController:alertController animated:YES completion:nil];
    
    
}

-(void)pushToViewControllerWhenClickPushMessageWith:(NSDictionary*)msgDic{
    
    [[NSNotificationCenter defaultCenter]postNotificationName:@"JPushJumpToMySchemeVC" object:nil];
}


-(void)dealloc{
    
    [[NSNotificationCenter defaultCenter]removeObserver:self];
    
}

@end
